//
//  HomeTableViewController.swift
//  TakeTime
//
//  Created by bachelor on 16/10/22.
//  Copyright © 2016年 bachelor. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {

    
    var isPresented: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        visitorView?.setupInfo(iconName: "visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        setupNavigationBar()
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        visitorView?.startAnimation()
    }
    
    private func setupNavigationBar() {
        // 判断用户是否登录
        if sharedUserAccount == nil {
            return
        }
        
        // 1. 设置按钮
        let leftBtn = UIButton()
        // 尺寸一定要设
        leftBtn.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch"), for: UIControlState.normal);
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), for: UIControlState.highlighted)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBtn)
        
        let rightBtn = UIButton()
        rightBtn.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        rightBtn.setImage(UIImage(named: "navigationbar_pop"), for: UIControlState.normal);
        rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), for: UIControlState.highlighted)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        // 2. 设置标题
        let name = sharedUserAccount!.name!
        let titleButton = HomeTitleBtn()
        titleButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        titleButton.setTitleColor(UIColor.black, for: UIControlState.normal)
        titleButton.titleLabel?.font = UIFont.systemFont(ofSize: 17.0)
        titleButton.setTitle(name + " ", for: UIControlState.normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), for: UIControlState.normal)
        titleButton.addTarget(self, action: #selector(HomeTableViewController.pop), for: .touchUpInside)
        
        navigationItem.titleView = titleButton
    }
    
    func pop() {
        let sb = UIStoryboard.init(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateInitialViewController()!
        
        // 1.设置转场代理
        vc.transitioningDelegate = self
        // 2.设置转场模式
        vc.modalPresentationStyle = .custom
        
        self.present(vc, animated: true, completion: nil)
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }

    /*
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension HomeTableViewController: UIViewControllerTransitioningDelegate {
    
    // 负责转场的控制器对象
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return PresentationController.init(presentedViewController: presented, presenting: presenting)
    }
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresented = true
        return self
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresented = false
        return self
    }
    
}

extension HomeTableViewController: UIViewControllerAnimatedTransitioning {
    
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVC = transitionContext.viewController(forKey: .from)
        let toVC = transitionContext.viewController(forKey: .to)
        
        if isPresented {
            if let toView = toVC?.view {
                // 1.将视图添加到容器中
                transitionContext.containerView.addSubview(toView)
                // 2.动画实现
                
                /// 2.1 toView的起始transform
                toView.transform = CGAffineTransform(scaleX: 1.0, y: 0)
                
                
                
                toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
                
                
                
                
                UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 10.0, options: .curveEaseIn, animations: {
                    toView.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    // 3.动画完结
                    transitionContext.completeTransition(true)
                })
            }
        }else {
            if let fromView = fromVC?.view {
                
                UIView.animate(withDuration: 0.5, animations: { 
                    fromView.transform = CGAffineTransform.init(scaleX: 1.0, y: 0.001)
                }, completion: { (_) in
                    fromView.removeFromSuperview()
                    transitionContext.completeTransition(true)

                })
            }
            
            
        }
        
        
    }
    
}
